<template>
  <div class="application-management-container">
    <div class="page-header">
      <h2>申请管理</h2>
      <p>管理所有课题申请记录，包括审核、查看详情等操作</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="filter-card">
      <el-form
        :inline="true"
        :model="searchForm"
        class="filter-form"
      >
        <el-form-item label="项目ID">
          <el-input
            v-model="searchForm.project_id"
            placeholder="请输入项目ID"
            class="search-input small-input"
          />
        </el-form-item>

        <el-form-item label="申请人ID">
          <el-input
            v-model="searchForm.applicant_id"
            placeholder="请输入申请人ID"
            class="search-input small-input"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="filter-select"
          >
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="accepted" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已撤回" value="withdrawn" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 申请列表 -->
    <el-card class="table-card">
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="applicationList"
          border
          stripe
          :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': '500' }"
          class="application-table"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="id" label="申请ID" min-width="100" />
          <el-table-column prop="project_id" label="课题ID" min-width="100" />
          <el-table-column prop="applicant_id" label="申请人ID" min-width="120" />

          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              <el-tag
                :type="statusTypeMap[scope.row.status]?.type"  
                size="small"
              >
                {{ statusTypeMap[scope.row.status]?.label || '未知状态' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="apply_date" label="申请时间" min-width="160">
            <template #default="scope">
              {{ formatDate(scope.row.apply_date) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="updated_at" label="更新时间" min-width="160">
            <template #default="scope">
              {{ formatDate(scope.row.updated_at) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="180" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="text"
                @click="handleView(scope.row)"
                class="operation-btn"
              >
                查看
              </el-button>

              <template v-if="scope.row.status === 'pending'">
                <el-button
                  size="small"
                  type="text"
                  class="text-success operation-btn"
                  @click="handleApprove(scope.row)"
                  :loading="statusLoading[scope.row.id]"
                >
                  批准
                </el-button>

                <el-button
                  size="small"
                  type="text"
                  class="text-danger operation-btn"
                  @click="handleReject(scope.row)"
                  :loading="statusLoading[scope.row.id]"
                >
                  拒绝
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 拒绝申请弹窗 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝申请" width="40%">
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.feedback"
            type="textarea"
            rows="4"
            placeholder="请输入拒绝原因，将通知申请人"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { applicationApi } from '@/api/admin';
import type { Application } from '@/api/adminTypes.ts';
// import type { Project } from '@/api/adminTypes.ts';
// import { Row } from 'element-plus/lib/components/table-v2/src/components/index.js';

// 定义状态类型和映射

type StatusType = 'pending' | 'accepted' | 'rejected' | 'withdrawn';

const statusTypeMap: Record<StatusType, { label: string; type: string }> = {
  pending: { label: '待审核', type: 'warning' },
  accepted: { label: '已通过', type: 'success' },
  rejected: { label: '已拒绝', type: 'danger' },
  withdrawn: { label: '已撤回', type: 'info' }
};
// 安全访问状态映射
const getStatusInfo = (status: StatusType) => {
  return statusTypeMap[status];
}

// 示例：获取申请列表
const fetchApplications = async () => {
  try {
    const res = await applicationApi.getApplications();
    applicationList.value = res.data;
  } catch (error) {
    console.error('获取申请列表失败:', error);
  }
}

// 搜索表单
const searchForm = reactive({
  project_id: '',
  applicant_id: '',
  status: ''
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 表格数据
const applicationList = ref<Application[]>([]);
const loading = ref(false);
const statusLoading = ref<Record<number, boolean>>({});

// 拒绝申请弹窗
const rejectDialogVisible = ref(false);
const rejectForm = reactive({
  feedback: ''
});
const currentRejectId = ref<number | null>(null);

// 获取申请列表
const getApplications = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {
      page: pagination.page,
      size: pagination.size,
      status: searchForm.status || undefined,
      project_id: searchForm.project_id || undefined,
      applicant_id: searchForm.applicant_id || undefined
    };

    const res = await applicationApi.getApplications(params);
    applicationList.value = res.data;
    //console.log("获取申请列表：",applicationList.value)
    pagination.total = res.data.total || 0;
  } catch (error) {
    console.error('获取申请列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1; // 重置到第一页
  getApplications();
};

// 重置表单
const resetForm = () => {
  searchForm.project_id = '';
  searchForm.applicant_id = '';
  searchForm.status = '';
  pagination.page = 1;
  getApplications();
};

// 查看申请详情
const handleView = (row: Application) => {
  // 这里可以跳转到申请详情页或打开详情弹窗
  console.log('查看申请:', row);
  ElMessage.info('申请详情功能待实现');
};

// 修改批准申请方法
const handleApprove = async (row: Application) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      `确定要批准申请ID【${row.id}】吗？`,
      '操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    );

    if (confirmResult === 'confirm') {
      statusLoading.value[row.id] = true;
      await applicationApi.updateApplicationStatus(row.id,
        'accepted',
        '申请已通过'
      );
      ElMessage.success('申请已批准');
      getApplications();
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批准申请失败:', error);
      ElMessage.error('批准失败，请重试');
    }
  } finally {
    if (row.id in statusLoading.value) {
      statusLoading.value[row.id] = false;
    }
  }
};

// 拒绝申请 - 打开弹窗
const handleReject = (row: Application) => {
  currentRejectId.value = row.id;
  rejectForm.feedback = '';
  rejectDialogVisible.value = true;
};

// 确认拒绝申请
// 修改确认拒绝方法
const confirmReject = async () => {
  if (!currentRejectId.value) return;

  if (!rejectForm.feedback.trim()) {
    ElMessage.warning('请输入拒绝原因');
    return;
  }

  try {
    statusLoading.value[currentRejectId.value] = true;
    await applicationApi.updateApplicationStatus(currentRejectId.value,
      'rejected',
      rejectForm.feedback
    );

    ElMessage.success('申请已拒绝');
    rejectDialogVisible.value = false;
    getApplications();
  } catch (error) {
    console.error('拒绝申请失败:', error);
    ElMessage.error('拒绝失败，请重试');
  } finally {
    if (currentRejectId.value in statusLoading.value) {
      statusLoading.value[currentRejectId.value] = false;
    }
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  getApplications();
};

// 当前页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  getApplications();
};

// 定义时间格式化函数，明确参数和返回值类型
const formatDate = (dateString: string | undefined | null): string => {
  // 处理空值或undefined
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString);
    
    // 验证日期是否有效
    if (isNaN(date.getTime())) {
      return '无效时间';
    }
    
    // 获取年月日时分，并确保两位数格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('时间格式化失败:', error);
    return '格式化错误';
  }
};

// 如果需要，可以定义表格行数据的类型接口（根据实际数据结构调整）
interface TableRow {
  CreatedAt: string;
  // 其他字段...
  // id: number;
  // name: string;
}

// 初始化页面加载数据
getApplications();
</script>

<style scoped lang="scss">
.application-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;

  h2 {
    margin-bottom: 5px;
    color: #1f2937;
  }

  p {
    color: #6b7280;
    font-size: 14px;
  }
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.filter-form {
  padding: 15px 0;

  .search-input {
    width: 200px;
  }

  .small-input {
    width: 140px;
  }

  .filter-select {
    width: 140px;
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.table-container {
  overflow-x: auto;
}

.application-table {
  width: 100%;

  .operation-btn {
    margin: 0 5px;
  }
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

@media (max-width: 768px) {
  .filter-form {
    .el-form-item {
      margin-bottom: 10px;
      width: 100%;
    }

    .search-input, .filter-select {
      width: 100%;
    }
  }
}
</style>
